package com.charles.video.common.log.aspect;

import com.charles.video.api.domain.MemberLog;
import com.charles.video.common.core.utils.IpUtils;
import com.charles.video.common.log.annotation.Log;
import com.charles.video.common.log.service.AsyncLogService;
import com.charles.video.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Autowired
    private AsyncLogService logService;

    @Around("@annotation(com.charles.video.common.log.annotation.Log)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Log logBehavior = signature.getMethod().getAnnotation(Log.class);
        if (logBehavior != null) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String clientIP = IpUtils.getIpAddr(request);
            MemberLog memberLog = new MemberLog();
            memberLog.setMember_id(SecurityUtils.getMemberId());
            memberLog.setIp_addr(clientIP);
            memberLog.setBehavior(logBehavior.behavior());
            logService.saveSysLog(memberLog);
            log.info("===============logBehavior==================");
            log.info(clientIP + ": " + logBehavior.behavior());
        }
        try {
            Object obj = proceedingJoinPoint.proceed();
            return obj;
        } catch (Throwable throwable) {
            throw throwable;
        }
    }

}
